// 配置管理模块

// 配置管理类
class ConfigManager {
    constructor() {
        this.aiProviderSelect = document.getElementById('ai-provider');
        this.apiKeyContainer = document.getElementById('api-key-container');
        this.apiKeyInput = document.getElementById('api-key');
        this.useFallbackCheckbox = document.getElementById('use-fallback');
        this.connectionStatus = document.getElementById('connection-status');
        
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.loadConfig();
    }
    
    bindEvents() {
        // AI提供商选择事件
        this.aiProviderSelect.addEventListener('change', () => {
            this.toggleApiKeyVisibility();
            this.saveConfig();
        });
        
        // API密钥输入事件
        this.apiKeyInput.addEventListener('input', window.utils.debounce(() => {
            this.saveConfig();
        }, 500));
        
        // 回退选项事件
        this.useFallbackCheckbox.addEventListener('change', () => {
            this.saveConfig();
        });
    }
    
    toggleApiKeyVisibility() {
        if (this.aiProviderSelect.value === 'openai') {
            this.apiKeyContainer.style.display = 'block';
        } else {
            this.apiKeyContainer.style.display = 'none';
        }
    }
    
    saveConfig() {
        const config = {
            aiProvider: this.aiProviderSelect.value,
            apiKey: this.apiKeyInput.value,
            useFallback: this.useFallbackCheckbox.checked
        };
        
        localStorage.setItem('aiChatConfig', JSON.stringify(config));
    }
    
    loadConfig() {
        const savedConfig = localStorage.getItem('aiChatConfig');
        if (savedConfig) {
            const config = JSON.parse(savedConfig);
            
            this.aiProviderSelect.value = config.aiProvider || 'mock';
            this.apiKeyInput.value = config.apiKey || '';
            this.useFallbackCheckbox.checked = config.useFallback !== undefined ? config.useFallback : true;
            
            this.toggleApiKeyVisibility();
        }
    }
    
    getConfig() {
        return {
            aiProvider: this.aiProviderSelect.value,
            apiKey: this.apiKeyInput.value,
            useFallback: this.useFallbackCheckbox.checked
        };
    }
    
    setConnectionStatus(connected, message = '') {
        if (connected) {
            this.connectionStatus.innerHTML = '● 已连接';
            this.connectionStatus.style.color = '#4cd964';
        } else {
            this.connectionStatus.innerHTML = '● 连接失败' + (message ? `: ${message}` : '');
            this.connectionStatus.style.color = '#ff3b30';
        }
    }
}

// 导出配置管理器
window.configManager = new ConfigManager();